<?php

namespace app\admin\controller;

use app\common\model\AdminLoginLog;
use app\MyController;
use think\facade\View;
use think\facade\Db;
use \think\facade\Request;
use app\common\model\Admin;
use app\common\model\AdminOperationLog;
use app\common\model\AdminQuanxian;


/**
 * 商户后台控制器基类
 */
class Base extends MyController
{
    public $page = '10';
    public $page_num = '10';
    public $admin_id = 0;

    /**
     * 后台初始化
     */
    public function initialize()
    {
        if (!session('admin_id') || !session('admin_token')) {
            echo "<script>location.href='/admin/login'</script>";
            die;
        }

        $this->admin_id = session('admin_id');
        $admin_token = session('admin_token');
        $admin_info = Admin::where(['id' => $this->admin_id])->field('id,get_time,random,token,password')->find();
        if (!$admin_info || time() > ($admin_info['get_time'] + 3600)) {
            // echo "<script>location.href='/admin/login'</script>";
            // die;
        }
        if ($admin_token !== sha1(md5($admin_info['id'] . $admin_info['password'] . $admin_info['random']))) {
            echo "<script>location.href='/admin/login'</script>";
            die;
        }
        if ($admin_info['token'] !== $admin_token) {
            echo "<script>location.href='/admin/login'</script>";
            die;
        }
        Admin::where(['id' => $this->admin_id])->field('id,get_time')->update(['get_time' => time()]);
        $this->config = getConfig('base');
        View::assign("config", $this->config);
        $this->admin_id = session('admin_id');
        $menulist = $this->getMyMenuList();
        View::assign("menulist", $menulist);
        $controller = strtolower(request()->controller());
        $action = strtolower(request()->action());
        if ($action != 'index' && $action != 'welcome') {
            $operation = $controller . '/' . $action;
            $content = request()->param();
            #记录操作日志
            AdminOperationLog::insert([
                'a_id' => $this->admin_id,
                'ip' => ip2long(request()->ip()),
                'operation' => $operation,
                'content' => json_encode($content),
                'addtime' => time(),
            ]);
        }

    }


    #获取菜单
    public function getMyMenuList()
    {
        $adminInfo = Admin::field('id,qid')->where(['id' => $this->admin_id])->find();
        if ($adminInfo['qid'] == 0) {
            $new_menu = config('menu');
        } else {
            $menu = config('menu');
            $q_info = AdminQuanxian::field('quanxian')->where(['id' => $adminInfo['qid']])->find();
            $quanxian = explode(',', $q_info['quanxian']);
            $new_menu = [];
            foreach ($menu as $k => $v) {
                foreach ($v['son'] as $s => $so) {
                    $name = $so['name'];
                    if (in_array($name, $quanxian)) {
                        if (isset($new_menu[$k]['name'])) {
                            $new_menu[$k]['son'][] = [
                                'url' => $so['url'],
                                'name' => $so['name'],
                            ];
                        } else {
                            $new_menu[$k] = [
                                'name' => $v['name'],
                                'son' => [[
                                    'url' => $so['url'],
                                    'name' => $so['name'],
                                ],],
                            ];
                        }

                    }
                }
            }

        }
        return $new_menu;
    }

    // 查询多条数据-不分页
    public function getList($table, $where = array(), $field = '*', $order = "")
    {
        $list = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->select();
        $data = $list;
        return $data;
    }

    // 查询多条数据-分页
    public function getMulList($table, $where = '', $field = '*', $order = '')
    {
        $list = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->paginate($this->page_num, false, ['query' => request()->param(), 'type' => 'bootstrap2']);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['page'] = $page;
        $data['count'] = $list->total();
        return $data;
    }

    // 多表联查分页
    public function getTablesList($table, $where, $alias, $join, $field, $order)
    {
        $list = DB::name($table)
            ->where($where)
            ->alias($alias)
            ->join($join)
            ->field($field)
            ->order($order)
            ->paginate($this->page_num, false, ['query' => request()->param(), 'type' => 'bootstrap2']);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['page'] = $page;
        $data['count'] = $list->total();
        return $data;
    }

    // 查询多条数据-分页
    public function getMulListQuery($table, $where = '', $field = '*', $order = '')
    {
        $list = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->paginate(['list_rows' => 10, 'query' => request()->param()]);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['page'] = $page;
        $data['count'] = $list->total();
        return $data;
    }

    /**
     * 成功数据返回
     * @param string $msg
     * @param array $data
     * @return \think\response\Json
     */
    protected function succ($msg = '', $data = array())
    {
        if (empty($data)) {
            $data = array();
        }
        $result = array(
            "msg" => $msg,
            "status" => 1,
            "data" => $data
        );

        return json($result);
    }

    /**
     * 失败数据返回
     * @param string $msg
     * @param array $data
     * @return \think\response\Json
     */
    protected function err($msg = '', $data = array())
    {
        if (empty($data)) {
            $data = array();
        }
        $result = array(
            "msg" => $msg,
            "status" => 0,
            "data" => $data
        );
        return json($result);
    }

    /**
     * 查询多条数据自定义分页
     * @param $table
     * @param string $where
     * @param string $field
     * @param string $order
     * @param int $page_num
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function getMulListLimit($table, $where = '', $field = '*', $order = '', $page_num = 10)
    {
        $list = Db::name($table)
            ->where($where)
            ->field($field)
            ->order($order)
            ->paginate($page_num, false, ['query' => request()->param()]);
        $page = $list->render();
        $data['list'] = $list->toArray()['data'];
        $data['page'] = $page;
        $data['count'] = $list->total();
        return $data;
    }

}
